package com.ashlikun.keeplive

import android.app.AlarmManager
import android.app.Application.ALARM_SERVICE
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.core.app.AlarmManagerCompat
import com.ashlikun.keeplive.receiver.CheckServiceReceiver

/**
 * 作者　　: 李坤
 * 创建时间: 2024/9/30　16:42
 * 邮箱　　：496546144@qq.com
 *
 * 功能介绍：
 */
class AlarmManageHelp private constructor() {
    val alarmManager by lazy { KeepLive.app.getSystemService(ALARM_SERVICE) as AlarmManager }
    val pendingIntent by lazy { PendingIntent.getBroadcast(KeepLive.app, requestCode, Intent(KeepLive.app, CheckServiceReceiver::class.java), PendingIntent.FLAG_IMMUTABLE) }
    var isStart = false
        private set

    //设置任务的触发时间间隔
    var interval: Long = 30 * 1000

    companion object {
        private val instance by lazy { AlarmManageHelp() }
        fun get(): AlarmManageHelp = instance
        const val requestCode = 7896712

        // 是否使用RTC_WAKEUP  true:当设备关闭时，它将唤醒设备
        // 是否使用RTC_WAKEUP  false:此警报不会唤醒设备；如果它在设备睡眠时关闭，则要等到设备下次唤醒时才能发送。
        var IS_RTC_WAKEUP = false
    }

    val stopReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            KeepLive.loge("AlarmManageHelp 我接收了关闭通知")
            cancel()
        }
    }

    init {
        KeepLive.registerReceiver(KeepLive.app, stopReceiver, IntentFilter().apply {
            addAction(KeepLive.RECEIVER_KEEP_STOP)
        })
    }

    /**
     * 使用AlarmManager 唤醒服务
     * 需要权限 <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
     */
    fun startAlarmManager(checkMainProcess: Boolean = true) {
        if (checkMainProcess && !KeepLive.isMainProcess()) return
        val type = if (IS_RTC_WAKEUP) AlarmManager.RTC_WAKEUP else AlarmManager.RTC
        // 设置任务的触发时间
        alarmManager.cancel(pendingIntent)
        AlarmManagerCompat.setExactAndAllowWhileIdle(alarmManager, type, System.currentTimeMillis() + interval, pendingIntent)
        // 重复
//        alarmManager.setRepeating(type, System.currentTimeMillis() + interval, interval, pendingIntent)
        isStart = true
    }

    fun cancel() {
        isStart = false
        alarmManager.cancel(pendingIntent)
    }
}